<template>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="article-list">
    <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :error.sync="error" error-text="请求失败，点击重新加载">
      <!-- <van-cell
      v-for="item in list"
      :key="item.art_id"
      :title="item.title" /> -->
      <article-item v-for="(item, index) in list" :key="index" :article="item" />
    </van-list>
  </van-pull-refresh>
</template>

<script>
import { getArticleList } from '@/api/user'
import ArticleItem from '@/components/article-item'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  data () {
    return {
      list: [], // 数据
      loading: false,
      finished: false,
      timestamp: null, // 时间戳
      error: false,
      refreshing: false
    }
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  methods: {
    async onLoad () {
      try {
        const { data: res } = await getArticleList({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(), // 第一次使用是Date.now()，后续就是当前的
          with_top: 1
        })
        // console.log(res.data)
        const { results } = res.data
        this.list.push(...results)
        this.timestamp = res.data.pre_timestamp
        // console.log(this.list)
        this.loading = false // 结束当前的加载
        if (res.data.results.length === 0) { // 如果当前这一次数据请求回来是空的，说明数据已经加载完了
          this.finished = true
        }
        // 模拟错误
        // if (Math.random() > 0.5) {
        //   JSON.parse('asodihasdgas')
        // }
      } catch (err) {
        this.$toast.fail('获取文章列表失败！')
        this.error = true
      }
    },
    // 下拉刷新事件
    async onRefresh () {
      try {
        const { data: res } = await getArticleList({
          channel_id: this.channel.id,
          timestamp: Date.now(), // 第一次使用是Date.now()，后续就是当前的
          with_top: 1
        })
        const { results } = res.data
        this.list.unshift(...results) // 在最前面追加
        this.refreshing = false // 关闭下拉刷新效果
      } catch (err) {
        this.$toast.fail('获取数据失败')
        this.refreshing = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-list {
  height: 80vh;
  overflow-y: auto;
}
</style>
